package org.itboys.basetemplate.web;

import java.text.ParseException;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.time.DateUtils;
import org.itboys.baseobject.util.MultiFile;
import org.itboys.basetemplate.entity.TravelNote;
import org.itboys.basetemplate.entity.TravelNoteCat;
import org.itboys.basetemplate.service.TravelNoteCatService;
import org.itboys.basetemplate.service.TravelNoteService;
import org.itboys.commons.CommonConstants;
import org.itboys.commons.dto.ResultPageDOHelper;
import org.itboys.commons.utils.ajax.AjaxUtils;
import org.itboys.commons.utils.io.FileUtils;
import org.itboys.commons.utils.json.JsonUtils;
import org.itboys.framework.query.JsonPageUtils;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.framework.spring.controller.BaseController;
import org.itboys.mongodb.utils.page.Page;
import org.itboys.mongodb.utils.query.QueryParamUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

/**
 * 游记
 */
@RestController
@RequestMapping(value = "/back/travelNote")
public class TravelNoteController extends BaseController{

	@Autowired
	private TravelNoteCatService catService;
	@Autowired
	private TravelNoteService noteService;	
	@Autowired
	private ResourceHolder resourceHolder;
	/**
	 * 游记类型页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/catTab")
	public ModelAndView type(Integer parentId, Model model){
		model.addAttribute("parentId", parentId);
		return new ModelAndView("travelNote/catTab");
	}
	/**
	 * 列表页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toCatList")
	public ModelAndView toList(Integer type, Model model){
		model.addAttribute("type", type);
		return new ModelAndView("travelNote/catList");
	}
	/**
	 * 分页查询
	 * @param request
	 * @param response
	 */
	@RequestMapping("/catList")
	public void catList(HttpServletRequest request,HttpServletResponse response)throws ParseException {
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		if(request.getParameter("f_D_startTime")!=null && !"".equals(request.getParameter("f_D_startTime"))){
			Date startTime = DateUtils.parseDate(request.getParameter("f_D_startTime").trim(),CommonConstants.DATE.PARSE_FORMAT_ARR);
			param.put("createTime >=", startTime);
		}
		if(request.getParameter("f_D_endTime")!=null && !"".equals(request.getParameter("f_D_endTime"))){
			Date endTime = DateUtils.parseDate(request.getParameter("f_D_endTime").trim(),CommonConstants.DATE.PARSE_FORMAT_ARR);
			param.put("createTime <=", endTime);
		}
		Page<TravelNoteCat> pageNav = catService.pageQuery(param,request);
		JsonPageUtils.renderJsonPage(pageNav.getTotal(), pageNav.getData(), response);
	}
	/**
	 * 编辑页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toEditCat")
	public ModelAndView toEditCat(TravelNoteCat bean, Model model){
		Long id = bean.getId();
		if (id!=0L) {
			bean = catService.getById(id);
			model.addAttribute("operation", "alter");
		}else {
			model.addAttribute("operation", "add");
		}

		model.addAttribute("bean", bean);
		return new ModelAndView("travelNote/catForm");
	}
	/**
	 * 新增
	 * @param bean
	 * @param response
	 */
	@RequestMapping("/addCat")
	public void addCat(@ModelAttribute TravelNoteCat bean, MultiFile multiFile, Integer operation, HttpServletResponse response){
		try {
//			Map<String, MultipartFile> fileMap = multiFile.getFileMap();
//			MultipartFile travelNote = fileMap.get("image");
//			//logger.info("上传图片开始,upload img statrt*************"+travelNote);
//			if (travelNote != null && !travelNote.isEmpty()) {
//				String filePath = FileUtils.saveFile(travelNote.getInputStream(),	resourceHolder.getStringValue("fileUploadPath"), travelNote.getOriginalFilename(), travelNote.getContentType());
//				//logger.info("upload path=========="+resourceHolder.getStringValue("fileUploadPath"));
//				bean.setImage(filePath);
//			}
			if (operation!=null && operation==2) {
				bean.setStatus(2);
			}else {
				bean.setStatus(1);
			}
			bean.setIsDeleted(0);
			bean.setCreateTime(new Date());
			catService.save(bean);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getMsgResultDO(null, "操作成功!")));
		} catch (Exception e) {
			logger.error("add error", e);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getErrorResultDO(-1, "系统异常!")));
		}
	}
	/**
	 * 修改
	 * @param bean
	 * @param response
	 */
	@RequestMapping("/alterCat")
	public void alterCat(@ModelAttribute TravelNoteCat bean, MultiFile multiFile, Integer operation, HttpServletResponse response){
		try {
//			Map<String, MultipartFile> fileMap = multiFile.getFileMap();
//			MultipartFile travelNote = fileMap.get("image");
//			if (travelNote != null && !travelNote.isEmpty()) {
//				String filePath = FileUtils.saveFile(travelNote.getInputStream(),	resourceHolder.getStringValue("fileUploadPath"), travelNote.getOriginalFilename(), travelNote.getContentType());
//				bean.setImage(filePath);
//			}
			if (operation!=null) {
				if (operation==2) {
					bean.setStatus(2);
				}else if (operation==3) {
					bean.setStatus(1);
				}
			}
			bean.setUpdateTime(new Date());
			catService.modifyNotNull(bean);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getMsgResultDO(null, "操作成功!")));
		} catch (Exception e) {
			logger.error("alter error", e);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getErrorResultDO(-1, "系统异常!")));
		}
	}
	/**
	 * 异步删除
	 */
	@RequestMapping("/removeCat/{id}")
	public void removeCat(@PathVariable("id") String id,HttpServletResponse response){
		try {
			if (id!=null && !"".equals(id)) {
				String ids[] = id.split(",");
				for (String str : ids) {
					catService.update(Long.parseLong(str), "isDeleted", new Integer(1));
				}
			}
			AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(null, "操作成功!"));
		} catch (Exception e) {
			logger.error("remove error", e);
			AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
		}
	}
	/**
	 * tab页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/tab")
	public ModelAndView tab(Integer parentId, Model model){
		model.addAttribute("parentId", parentId);
		return new ModelAndView("travelNote/tab");
	}
	/**
	 * 列表页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toList")
	public ModelAndView towList(Integer catId, Model model){
		model.addAttribute("catId", catId);
		return new ModelAndView("travelNote/list");
	}
	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @throws ParseException 
	 */
	@RequestMapping("/list")
	public void list(HttpServletRequest request,HttpServletResponse response) throws ParseException{
		Map<String, Object> param = QueryParamUtils.builderQueryMap(request);
		if(request.getParameter("f_D_startTime")!=null && !"".equals(request.getParameter("f_D_startTime"))){
			Date startTime = DateUtils.parseDate(request.getParameter("f_D_startTime").trim(),CommonConstants.DATE.PARSE_FORMAT_ARR);
			param.put("createTime >=", startTime);
		}
		if(request.getParameter("f_D_endTime")!=null && !"".equals(request.getParameter("f_D_endTime"))){
			Date endTime = DateUtils.parseDate(request.getParameter("f_D_endTime").trim(),CommonConstants.DATE.PARSE_FORMAT_ARR);
			param.put("createTime <=", endTime);
		}
		if(request.getParameter("f_D_pstartTime")!=null && !"".equals(request.getParameter("f_D_pstartTime"))){
			Date startTime = DateUtils.parseDate(request.getParameter("f_D_pstartTime").trim(),CommonConstants.DATE.PARSE_FORMAT_ARR);
			param.put("publishTime >=", startTime);
		}
		if(request.getParameter("f_D_pendTime")!=null && !"".equals(request.getParameter("f_D_pendTime"))){
			Date endTime = DateUtils.parseDate(request.getParameter("f_D_pendTime").trim(),CommonConstants.DATE.PARSE_FORMAT_ARR);
			param.put("publishTime <=", endTime);
		}
		Page<TravelNote> pageNav = noteService.pageQuery(param,request);
		JsonPageUtils.renderJsonPage(pageNav.getTotal(), pageNav.getData(), response);
	}
	/**
	 * 编辑页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toEdit")
	public ModelAndView toEdit(TravelNote bean, Model model){
		Long id = bean.getId();
		if (id!=0L) {
			bean = noteService.getById(id);
			model.addAttribute("operation", "alter");
		}else{
			model.addAttribute("operation", "add");
		}
		model.addAttribute("bean", bean);
		return new ModelAndView("travelNote/form");
	}
	/**
	 * 新增
	 * @param bean
	 * @param response
	 */
	@RequestMapping("/add")
	public void add(@ModelAttribute TravelNote bean, MultiFile multiFile, String appType, Integer operation, HttpServletResponse response){
		try {
			Map<String, MultipartFile> fileMap = multiFile.getFileMap();
			String saveImageDir = resourceHolder.getStringValue("fileUploadPath");
			MultipartFile travelNote = fileMap.get("image");
			if (travelNote != null && !travelNote.isEmpty()) {
				String filePath = FileUtils.saveFile(travelNote.getInputStream(),	saveImageDir, travelNote.getOriginalFilename(), travelNote.getContentType());
				bean.setImage(filePath);
			}
			if (operation!=null && operation==2) {
				bean.setStatus(2);
			}else {
				bean.setStatus(1);
			}
			bean.setIsDeleted(0);
			bean.setCreateTime(new Date());
			noteService.save(bean);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getMsgResultDO(null, "操作成功!")));
		} catch (Exception e) {
			logger.error("add error", e);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getErrorResultDO(-1, "系统异常!")));
		}
	}
	/**
	 * 修改
	 * @param bean
	 * @param response
	 */
	@RequestMapping("/alter")
	public void alter(@ModelAttribute TravelNote bean, String appType, MultiFile multiFile, Integer operation, 
			HttpServletResponse response){
		try {
			Map<String, MultipartFile> fileMap = multiFile.getFileMap();
			String saveImageDir = resourceHolder.getStringValue("fileUploadPath");
			MultipartFile travelNote = fileMap.get("image");
			if (travelNote != null && !travelNote.isEmpty()) {
				String filePath = FileUtils.saveFile(travelNote.getInputStream(),	saveImageDir, travelNote.getOriginalFilename(), travelNote.getContentType());
				bean.setImage(filePath);
			}
			if (operation!=null) {
				if (operation==2) {
					bean.setStatus(2);
				}else if (operation==3) {
					bean.setStatus(1);
				}
			}
			bean.setUpdateTime(new Date());
			noteService.modifyNotNull(bean);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getMsgResultDO(null, "操作成功!")));
		} catch (Exception e) {
			logger.error("alter error", e);
			AjaxUtils.renderText(response, JsonUtils.objectToString(ResultPageDOHelper.getErrorResultDO(-1, "系统异常!")));
		}
	}
	/**
	 * 异步删除
	 */
	@RequestMapping("/remove/{id}")
	public void remove(@PathVariable("id") String id,HttpServletResponse response){
		try {
			if (id!=null && !"".equals(id)) {
				String ids[] = id.split(",");
				for (String str : ids) {
					noteService.update(Long.parseLong(str), "isDeleted", new Integer(1));
				}
			}
			AjaxUtils.renderJson(response, ResultPageDOHelper.getMsgResultDO(null, "操作成功!"));
		} catch (Exception e) {
			logger.error("remove error", e);
			AjaxUtils.renderJson(response, ResultPageDOHelper.getErrorResultDO(-1, "系统异常!"));
		}
	}
	/**
	 * 获取信息
	 * @param id
	 * @param response
	 */
	@RequestMapping("/get/{id}")
	public void get(@PathVariable("id") Long id,HttpServletResponse response){
		TravelNote bean = noteService.getById(id);
		AjaxUtils.renderJson(response, bean);
	}
	
}
